package br.com.unifebe.tcc.componente.GUI;

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.ParseException;

import javax.swing.JComboBox;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;

import br.com.unifebe.tcc.UTILS.Funcoes;
import br.com.unifebe.tcc.model.TipoPessoa;

public class JMLMaskEditCnpjCpf extends JMLMaskEdit {
	private JComboBox comboTipoPessoa;
	private String mask;
	/**
	 * 
	 */
	public JMLMaskEditCnpjCpf(JComboBox comboTipoPessoa) {
		super();
		this.comboTipoPessoa = comboTipoPessoa;
		this.comboTipoPessoa.addItemListener(new ItemListener(){
			@Override
			public void itemStateChanged(ItemEvent e) {
				if (e.getStateChange() == ItemEvent.SELECTED) {
					doMask();
				}
			}
		});
		this.addFocusListener(new FocusListener(){
			@Override
			public void focusGained(FocusEvent e) {}
			@Override
			public void focusLost(FocusEvent e) {}
		});
		doMask();
	}

	private void doMask() {
		if (this.comboTipoPessoa.getSelectedItem().equals( TipoPessoa.JURIDICA )) {
			mask = "##.###.###/####-##";
		} else if (this.comboTipoPessoa.getSelectedItem().equals( TipoPessoa.FISICA )) {
			mask = "###.###.###-##";
		} else {
			mask = "**************";
		}

		try {
			
			StringBuffer s = new StringBuffer(this.getText());
			s = Funcoes.limpaString(s);
			
			this.setText("");
			this.setValue(null);
			MaskFormatter formatter = new MaskFormatter(mask);
			DefaultFormatterFactory factory =  new DefaultFormatterFactory(formatter,formatter);
			this.setFormatterFactory(factory);
			this.setText(s.toString());
		} catch (ParseException pe) {
			Funcoes.showMessageErro(pe.getMessage(), pe);
		}
		this.updateUI();
	}
	

}
